
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using Microsoft.EnterpriseSingleSignOn.Interop;
using System.Runtime.InteropServices;
using System.Linq;
using System.Data.SqlClient;
using System.Configuration;


namespace BizTalk.Tools.SSOStorage
{
    public partial class ApplicationManager : Form
    {
        public ApplicationManager()
        {
            InitializeComponent();
        }

        private void btnCreateApp_Click(object sender, EventArgs e)
        {
            if (false == ValidateImport())
            {
                return;
            }

            //write to SSOPropBag to figure out how many rows we have
            SSOPropBag propertiesBag = new SSOPropBag();


            try
            {
                foreach (DataGridViewRow row in dgvFields.Rows)
                {
                    if (row.Cells[0].Value != null)
                    {
                        object propertyValue;
                        try
                        {
                            propertyValue = row.Cells[1].Value.ToString();
                        }
                        catch (NullReferenceException ex)
                        {
                            propertyValue = "";
                        }
                        propertiesBag.Write(row.Cells[0].Value.ToString(), ref propertyValue);
                    }
                }

                //set default configuration field values
                SSOConfigManager.SetConfigProperties(comboAppName.Text, txtIdentifier.Text, propertiesBag);

                // Track new application name for downstream listing
                SSOAppList.Instance.AddAppList(comboAppName.Text); //BEN


                //show success
                MessageBox.Show("Application Successfully Created", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                LoadApplicationsList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Occured.  Details: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRetrieveSettings_Click(object sender, EventArgs e)
        {

        }

        private void saveConfigurationToXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (comboAppName.Text == null || comboAppName.Text == string.Empty)
            {
                MessageBox.Show("Please enter an application name", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (fbdSavePath.ShowDialog() == DialogResult.OK)
                {
                    string path = fbdSavePath.SelectedPath;

                    SaveXmlConfiguration(path);

                    MessageBox.Show("Configuration saved successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
        }

        private void SaveXmlConfiguration(string path)
        {
            //generate temp guid
            string tempFileName = path + "\\SSO_" + comboAppName.Text + "_" + System.Guid.NewGuid().ToString() + ".xml";

            XmlTextWriter writer = new XmlTextWriter(tempFileName, Encoding.UTF8);

            //start document
            writer.WriteStartDocument();

            //start root
            writer.WriteStartElement("sso");

            writer.WriteStartElement("application");
            writer.WriteAttributeString("name", comboAppName.Text);

            writer.WriteElementString("description", txtDescription.Text);
            writer.WriteElementString("appUserAccount", txtAppUserAcct.Text);
            writer.WriteElementString("appAdminAccount", txtAppAdminAcct.Text);
            writer.WriteElementString("contactInfo", txtContactInfo.Text);
            //contactInfo

            int ordinalCount = 0;
            ArrayList fieldList = new ArrayList();
            //loop through field list
            foreach (DataGridViewRow row in dgvFields.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    writer.WriteStartElement("field");
                    

                    writer.WriteAttributeString("ordinal", ordinalCount.ToString());
                    writer.WriteAttributeString("label", row.Cells[0].Value.ToString());
                    writer.WriteAttributeString("masked", "no");                    
                    if(Convert.ToString(row.Cells[2].FormattedValue) != "ConfigProperties")
                    writer.WriteAttributeString("identifier", row.Cells[2].FormattedValue.ToString());
                    writer.WriteValue(row.Cells[1].FormattedValue.ToString());
                    writer.WriteEndElement();

                    fieldList.Add(row.Cells[0].Value.ToString());
                    ordinalCount++;
                }
            }

            writer.WriteStartElement("flags");
            writer.WriteAttributeString("configStoreApp", "yes");
            writer.WriteAttributeString("allowLocalAccounts", "yes");
            writer.WriteAttributeString("enableApp", "yes");
            writer.WriteEndElement();

            //close application
            writer.WriteEndElement();

            //close root
            writer.WriteEndElement();

            writer.Flush();
            writer.Close();
        }

        private void loadConfigurationFromXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ofdConfigFile.ShowDialog() == DialogResult.OK)
            {
                string path = ofdConfigFile.FileName;

                LoadXmlConfigFile(path);
            }
        }

        private void LoadXmlConfigFile(string path)
        {
            dgvFields.Rows.Clear();

            XmlDocument configDoc = new XmlDocument();
            configDoc.Load(path);

            string appName = configDoc.SelectSingleNode("//application/@name").InnerText;
            comboAppName.Text = appName;

            string description = configDoc.SelectSingleNode("//description").InnerText;
            txtDescription.Text = description;

            string appUserAcct = configDoc.SelectSingleNode("//appUserAccount").InnerText;
            txtAppUserAcct.Text = appUserAcct;

            string appAdminAcct = configDoc.SelectSingleNode("//appAdminAccount").InnerText;
            txtAppAdminAcct.Text = appAdminAcct;

            if (null != configDoc.SelectSingleNode("//contactInfo"))
            {
                string contactInfo = configDoc.SelectSingleNode("//contactInfo").InnerText;
                txtContactInfo.Text = contactInfo;
            }
            //grab fields
            XmlNodeList fields = configDoc.SelectNodes("//field");

            foreach (XmlNode field in fields)
            {
                int index = dgvFields.Rows.Add();
                DataGridViewRow dgvr = dgvFields.Rows[index];

                dgvr.Cells[0].Value = field.Attributes["label"].InnerText;
                dgvr.Cells[1].Value = field.InnerText;
                if (null != field.Attributes["identifier"] && Convert.ToString(field.Attributes["identifier"].InnerText) != "")
                    dgvr.Cells[2].Value = field.Attributes["identifier"].InnerText;
                else
                    dgvr.Cells[2].Value = "ConfigProperties";
            }


        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutMeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About aboutForm = new About();

            aboutForm.ShowDialog();
        }

        private void HandleFormLoad(object sender, EventArgs e)
        {
            LoadApplicationsList();
        }

        private int FieldCount
        {
            get
            {
                int count = 0;

                foreach (DataGridViewRow row in dgvFields.Rows)
                {
                    if (null != row.Cells[0].Value && null != row.Cells[1].Value)
                    {
                        ++count;
                    }
                }

                return count;
            }
        }

        private void LoadApplicationsList()
        {
            comboAppName.Items.Clear();

            string ConnecitonString = ConfigurationManager.AppSettings["ConnecitonString"];
            using (SqlConnection connection = new SqlConnection(ConnecitonString))
            {
                //string CommandText = "SELECT TOP 1000 [fi_app_name], [fi_label] FROM [SSODB].[dbo].[SSOX_FieldInfo] where [fi_app_name] like '%Utility.Archive.ContentManager.LoginDetails%'";
                string CommandText = "SELECT DISTINCT im_xa FROM [SSODB].[dbo].[SSOX_IndividualMapping] where im_xa not like '%{%'";
                connection.Open();
                SqlCommand sqlCommand = new SqlCommand(CommandText, connection);

                SqlDataReader reader = sqlCommand.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        comboAppName.Items.Add(reader["im_xa"].ToString());
                    }
                }
            }
        }


        private bool ValidateRetreive()
        {
            bool valid = true;

            if (true == String.IsNullOrEmpty(comboAppName.Text))
            {
                errorAdminAccount.SetError(comboAppName, "Must specify an application name");
                valid = false;
            }

            return valid;
        }

        private bool ValidateImport()
        {
            bool valid = true;

            if (true == String.IsNullOrEmpty(comboAppName.Text))
            {
                errorAdminAccount.SetError(comboAppName, "Must specify an application name");
                valid = false;
            }

            if (true == String.IsNullOrEmpty(txtAppAdminAcct.Text))
            {
                errorAdminAccount.SetError(txtAppAdminAcct, "Must specific an admin level access group");
                valid = false;
            }

            if (true == String.IsNullOrEmpty(txtAppUserAcct.Text))
            {
                errorAdminAccount.SetError(txtAppUserAcct, "Must specific a general user level access group");
                valid = false;
            }

            if (0 == FieldCount)
            {
                errorAdminAccount.SetError(dgvFields, "Must define at least one field with an associated value");
                valid = false;
            }

            return valid;
        }

        private void btnDeleteApplication_Click(object sender, EventArgs e)
        {

            //if (true == SSOConfigManager.ApplicationExists(comboAppName.Text))
            //{
            //    string applicationName = comboAppName.Text;
            //    SSOConfigManager.DeleteApplication(comboAppName.Text);
            //    SSOAppList.Instance.DeleteAppList(comboAppName.Text);
            //    LoadApplicationsList();
            //    comboAppName.Text = "";
            //    dgvFields.Rows.Clear();
            //    MessageBox.Show("Application " + applicationName + " has been deleted");
            //}
        }



        private void btnDeleteApplication_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("Please confirm", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
            {
                if (true == SSOConfigManager.ApplicationExists(comboAppName.Text))
                {
                    string applicationName = comboAppName.Text;
                    SSOConfigManager.DeleteApplication(comboAppName.Text);
                    SSOAppList.Instance.DeleteAppList(comboAppName.Text);
                    LoadApplicationsList();
                    comboAppName.Text = "";
                    dgvFields.Rows.Clear();
                    MessageBox.Show("Application " + applicationName + " has been deleted");
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {


            SSOPropBag propertiesBag = new SSOPropBag();

            //write to SSOPropBag to figure out how many rows we have


            try
            {
                foreach (DataGridViewRow row in dgvFields.Rows)
                {
                    if (row.Cells[0].Value != null)
                    {
                        object propertyValue;
                        try
                        {
                            propertyValue = row.Cells[1].Value.ToString();
                        }
                        catch (NullReferenceException ex)
                        {
                            propertyValue = "";
                        }
                        propertiesBag.Write(row.Cells[0].Value.ToString(), ref propertyValue);
                    }
                }

                //create and enable application
                SSOConfigManager.CreateConfigStoreApplication(comboAppName.Text, txtDescription.Text, txtAppUserAcct.Text, txtAppAdminAcct.Text, propertiesBag, txtContactInfo.Text);

                if (false == ValidateImport())
                {
                    return;
                }

                //set default configuration field values
                SSOConfigManager.SetConfigProperties(comboAppName.Text, txtIdentifier.Text, propertiesBag);

                // Track new application name for downstream listing
                SSOAppList.Instance.AddAppList(comboAppName.Text); //BEN


                //show success
                MessageBox.Show("Application Successfully Created", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                LoadApplicationsList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Occured.  Details: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnRetrieveAllSettings_Click(object sender, EventArgs e)
        {

            if (false == ValidateRetreive())
            {
                return;
            }

            dgvFields.Rows.Clear();

            string appName = comboAppName.Text;


            if (appName != null || appName != string.Empty)
            {
                try
                {
                    string appUserAcct, appAdminAcct, description, contactInfo;

                    string ConnecitonString = ConfigurationManager.AppSettings["ConnecitonString"];
                    using (SqlConnection connection = new SqlConnection(ConnecitonString))
                    {
                        //string CommandText = "SELECT TOP 1000 [fi_app_name], [fi_label] FROM [SSODB].[dbo].[SSOX_FieldInfo] where [fi_app_name] like '%Utility.Archive.ContentManager.LoginDetails%'";
                        string CommandText = "SELECT DISTINCT im_ntu FROM [SSODB].[dbo].[SSOX_IndividualMapping] where im_xa = " + "'" + appName + "'";
                        connection.Open();
                        SqlCommand sqlCommand = new SqlCommand(CommandText, connection);

                        SqlDataReader reader = sqlCommand.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                HybridDictionary props = SSOConfigManager.GetConfigProperties(appName, reader.GetString(0), out description, out contactInfo, out appUserAcct, out appAdminAcct);
                                txtDescription.Text = description;
                                txtAppAdminAcct.Text = appAdminAcct;
                                txtAppUserAcct.Text = appUserAcct;
                                txtContactInfo.Text = contactInfo;

                                foreach (DictionaryEntry appProp in props)
                                {
                                    int index = dgvFields.Rows.Add();
                                    DataGridViewRow dgvr = dgvFields.Rows[index];

                                    dgvr.Cells[0].Value = appProp.Key.ToString();
                                    dgvr.Cells[1].Value = appProp.Value.ToString();
                                    dgvr.Cells[2].Value = reader.GetString(0);

                                }
                            }
                        }
                        connection.Close();
                    }



                }
                catch (COMException comEx)
                {
                    MessageBox.Show("Error occurred. " + comEx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error Occured.  Details: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Please enter an application name.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnRetrive_Click(object sender, EventArgs e)
        {

            if (false == ValidateRetreive())
            {
                return;
            }

            dgvFields.Rows.Clear();

            string appName = comboAppName.Text;


            if (appName != null || appName != string.Empty)
            {
                try
                {
                    string appUserAcct, appAdminAcct, description, contactInfo;

                    string ConnecitonString = ConfigurationManager.AppSettings["ConnecitonString"];
                    HybridDictionary props = SSOConfigManager.GetConfigProperties(appName, txtIdentifier.Text.TrimEnd(), out description, out contactInfo, out appUserAcct, out appAdminAcct);
                    txtDescription.Text = description;
                    txtAppAdminAcct.Text = appAdminAcct;
                    txtAppUserAcct.Text = appUserAcct;
                    txtContactInfo.Text = contactInfo;

                    foreach (DictionaryEntry appProp in props)
                    {
                        int index = dgvFields.Rows.Add();
                        DataGridViewRow dgvr = dgvFields.Rows[index];

                        dgvr.Cells[0].Value = appProp.Key.ToString();
                        dgvr.Cells[1].Value = appProp.Value.ToString();
                        dgvr.Cells[2].Value = txtIdentifier.Text.TrimEnd();

                    }
                }
                catch (COMException comEx)
                {
                    MessageBox.Show("Error occurred. " + comEx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error Occured.  Details: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Please enter an application name.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void btnDelete_Click(object sender, EventArgs e)
        {
            SSOConfigManager.deleteConfigProperties(comboAppName.Text, txtIdentifier.Text);
            MessageBox.Show("Config. has been deleted.");
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void btnSaveAll_Click(object sender, EventArgs e)
        {
            if (false == ValidateImport())
            {
                return;
            }


            try
            {

                DataTable myDT = new DataTable("ConfigProperties");
                DataColumn column;
                DataRow row;

                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "key";
                // Add the column to the DataColumnCollection.
                myDT.Columns.Add(column);

                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "value";
                myDT.Columns.Add(column);

                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "identifier";
                myDT.Columns.Add(column);

                foreach (DataGridViewRow drow in dgvFields.Rows)
                {
                    if (drow.IsNewRow != true)
                    {

                        string identifier = Convert.ToString(drow.Cells[2].Value);
                        if (identifier == string.Empty)
                            identifier = "ConfigProperties";
                        myDT.Rows.Add(drow.Cells[0].Value.ToString(), drow.Cells[1].Value.ToString(), identifier);
                    }
                }

                List<string> identifiers = (from DataRow dr in myDT.Rows
                                            orderby (string)dr["identifier"]
                                            select (string)dr["identifier"]).Distinct().ToList();



                foreach (string identifier in identifiers)
                {

                    try
                    {
                        SSOConfigManager.deleteConfigProperties(comboAppName.Text, identifier);
                    }
                    catch { }

                    //write to SSOPropBag to figure out how many rows we have
                    SSOPropBag propertiesBag = new SSOPropBag();
                    foreach (DataGridViewRow drow in dgvFields.Rows)
                    {
                        if (Convert.ToString(drow.Cells[2].Value) == string.Empty) drow.Cells[2].Value = "ConfigProperties";
                        if (Convert.ToString(drow.Cells[0].Value) != string.Empty && Convert.ToString(drow.Cells[2].Value) == identifier && Convert.ToString(drow.Cells[1].Value) != string.Empty)
                        {
                            object propertyValue;
                            propertyValue = Convert.ToString(drow.Cells[1].Value);

                            propertiesBag.properties.Add(Convert.ToString(drow.Cells[0].Value), propertyValue);
                        }
                    }

                    SSOConfigManager.UpdateConfigStoreApplication(comboAppName.Text, txtDescription.Text, txtAppUserAcct.Text, txtAppAdminAcct.Text, propertiesBag, txtContactInfo.Text);
                    SSOConfigManager.SetConfigProperties(comboAppName.Text, identifier, propertiesBag);

                }

                //show success
                MessageBox.Show("Application Successfully Created", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                LoadApplicationsList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Occured.  Details: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}